/**
 * This javascript file handles page rendering and events.
 * 
 * @author 		Tobin Bradley
 * @license 	MIT
 */


/**
 * Document Ready and Window Load events.
 */
$(document).ready(function () {

    // Menu	
    $('ul.sf-menu').supersubs({
        minWidth: 12,   // minimum width of sub-menus in em units 
        maxWidth: 27,   // maximum width of sub-menus in em units 
        extraWidth: 1     // extra width can ensure lines don't sometimes turn over 
        // due to slight rounding differences and font-family 
    }).superfish();
   
    //Map Controlls
    $("#mapcontrols").buttonset();
    $("#mapcontrols input:radio").click(function () { alert($(this)[0].id); });
    $("#toolbar").fadeIn("slow");
    
    // Accordions
    $('.accordion-item').accordion({ header: "h3", collapsible: true, autoHeight: false, create: function (event, ui) { $(this).fadeIn("slow"); } }).bind("accordionchange", function (event, ui) {
        if (ui.newHeader[0]) {
            processAccordionDataChange(ui.newHeader[0].id);
        }
    });

    // Tabs
    $('#left-tabs').tabs({
        create: function (event, ui) { return; $(this).fadeIn("slow"); }
    });

    // Dialogs
    $("#search-dialog").dialog({ width: $("#searchdiv").width(), autoOpen: false, show: 'fade', hide: 'fade' });

    // Click events
    $("#searchdiv p a,  #searchoptions").click(function () { $('#search-dialog').dialog('open') });
    $("#searchinput").click(function () { $(this).select(); });

    // GPS   
    if (Modernizr.geolocation) {
        $(".gpslocation").show();
        $("#gogpslocation").click(function () {
            if (typeof gpsWatch != "number") {
                $("#gogpslocation").text("Stop Following My Location");
                gpsWatch = navigator.geolocation.watchPosition(
					function (position) {
					    (typeof position.coords.altitude == "undefined") ? altitude = position.coords.altitude + "m" : altitude = "Unknown";
					    isNaN(position.coords.speed) ? speed = "Unknown" : speed = position.coords.speed + "m/sec";
					    addMarker(position.coords.longitude, position.coords.latitude, 2, "<h5>Estimated Current Position</h5><p>Accuracy: " + position.coords.accuracy + "m<br />Timestamp: " + position.timestamp + "<br />Altitude: " + altitude + "<br />Speed: " + speed + "</p>");
					},
					function () { /* error handler */ },
					{ enableHighAccuracy: true, maximumAge: 30000, timeout: 27000 }
				);
            }
            else {
                gpsWatch = navigator.geolocation.clearWatch(gpsWatch);
                $("#gogpslocation").text("Follow My Location");
            }
        });
    }

    // Autocomplete
    $("#searchinput").autocomplete({
        minLength: 4,
        delay: 400,
        autoFocus: true,
        source: function (request, response) {

            $.ajax({
                url: wsbase + "v2/ws_geo_ubersearch.php",
                dataType: "jsonp",
                data: {
                    searchtypes: "Address,Library,School,Park,GeoName,Road,CATS,Intersection,PID",
                    query: request.term
                },
                success: function (data) {
                    if (data.total_rows > 0) {
                        response($.map(data.rows, function (item) {
                            return {
                                label: urldecode(item.row.displaytext),
                                value: item.row.displaytext,
                                responsetype: item.row.responsetype,
                                responsetable: item.row.responsetable,
                                getfield: item.row.getfield,
                                getid: item.row.getid
                            }
                        }));

                    }
                    else if (data.total_rows == 0) {
                        response($.map([{}], function (item) {
                            return {
                                // Message indicating nothing is found
                                label: "No records found."
                            }
                        }))
                    }
                    else if (data.total_rows == -1) {
                        response($.map([{}], function (item) {
                            return {
                                // Message indicating no search performed
                                label: "More information needed for search."
                            }
                        }))
                    }
                }
            })
        },
        select: function (event, ui) {
            // Run function on selected record
            if (ui.item.responsetype) {
                locationFinder(ui.item.responsetype, ui.item.responsetable, ui.item.getfield, ui.item.getid, ui.item.label, ui.item.value);
            }
        },
        open: function (event, ui) {
            $(this).keypress(function (e) {
                /* horizontal keys */
                if (e.keyCode == 13 || e.keyCode == 39) {
                    $($(this).data('autocomplete').menu.active).find('a').trigger('click');
                }
            });
            if ($("ul.ui-autocomplete li.ui-menu-item").length == 1) {
                // If there is only 1 result and it isn't a can't-find-squat message, select it                
                //if (theResult != "More information needed for search." && theResult != "No records found.") $($(this).data('autocomplete').menu.active).find('a').trigger('click');
            }
        }
    }).data("autocomplete")._renderMenu = function (ul, items) {
        var self = this, currentCategory = "";
        $.each(items, function (index, item) {
            if (item.responsetype != currentCategory && item.responsetype != undefined) {
                ul.append("<li class='ui-autocomplete-category'>" + item.responsetype + "</li>");
                currentCategory = item.responsetype;
            }
            self._renderItem(ul, item);
        });
    };

});

$(window).load(function() {
   
	// Detect arguments or localstorage
	if (getUrlVars()["matid"]) {		
		locationFinder("API", 'master_address_table', 'objectid', getUrlVars()["matid"]);
		if (getUrlVars()["category"]) {
		   jQuery.each($('#accordion-data h3'), function(i, val) {
			   if (val.id == getUrlVars()["category"] ) $('#accordion-data').accordion("activate", i);
		   });
		}
	}
   
});






/******************************************************************************/

/**
 * Accordion switch handler
 * @author 		Tobin Bradley
 * @license 	MIT
 */
function processAccordionDataChange(accordionValue) {
}






/******************************************************************************/

/**
 * Generic Functions
 * @author 		Tobin Bradley
 * @license 	MIT
 */

/**
 * Takes a string a URL encodes or decodes it
 * @param {string} str
 */
function urlencode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}
function urldecode(str) {
	str = str.replace('+', ' ');
	str = unescape(str);
	return str;
}


/**
 * Return whether a string is a number or not
 */
function isNumber (o) {
  return ! isNaN (o-0);
}


/**
 * Add commas to numeric values
 */
$.fn.digits = function(){ 
	return this.each(function(){ 
		$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
	})
}

/**
 * Read a page's GET URL variables and return them as an associative array.
 */
function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}




